#include "InputMappingDialog.h"
#include "ui_InputMappingDialog.h"
#include <QFormLayout>
#include <QCheckBox>
#include <QDebug>

InputMappingDialog::InputMappingDialog(QWidget* parent, const InputVector& defaultMappings)
  : QDialog(parent),
    mUI(new Ui::Form())
{
  mUI->setupUi(this);

  for (int i(0); i < defaultMappings.size(); ++i)
  {
    InputMapTab* imt(new InputMapTab(0, i, defaultMappings[i]));
    mUI->tabWidget->addTab(imt, "Input "+QString::number(i));
  }

  connect(mUI->okButton, SIGNAL(clicked()), this, SLOT(okButton()));
  connect(mUI->cancelButton, SIGNAL(clicked()), this, SLOT(cancelButton()));
}

InputMappingDialog::~InputMappingDialog()
{
}

void InputMappingDialog::okButton()
{
  accept();
}

void InputMappingDialog::cancelButton()
{
  reject();
}

InputMapping* InputMappingDialog::inputMapping(unsigned int inputNumber) const
{
  InputMapping* ret(0);
  if (inputNumber < static_cast<unsigned int>(mUI->tabWidget->count()))
  {
    InputMapTab* imt(qobject_cast<InputMapTab*>(mUI->tabWidget->widget(inputNumber)));
    if (imt)
    {
      ret = imt->inputMapping();
    }
  }
  return ret;
}

InputVector InputMappingDialog::remapInputs(const InputVector &defaultMappings)
{
  InputMappingDialog d(0, defaultMappings);
  QDialog::DialogCode dc(static_cast<QDialog::DialogCode>(d.exec()));
  if (dc == QDialog::Accepted)
  {
    return d.inputMappings();
  }
  else
  {
    return defaultMappings;
  }
}

InputVector InputMappingDialog::inputMappings() const
{
  InputVector ret(static_cast<unsigned int>(mUI->tabWidget->count()));
  for(int i(0); i < ret.size(); ++i)
  {
    InputMapTab* imt(qobject_cast<InputMapTab*>(mUI->tabWidget->widget(i)));
    if (imt)
    {
      ret[i] = imt->inputMapping();
    }
  }
  return ret;
}
